package com.desyang.server.net;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.Socket;

import com.desyang.common.message.Request;
import com.desyang.common.message.Response;
import com.desyang.server.provider.ServiceProvider;

import lombok.AllArgsConstructor;

@AllArgsConstructor
public class RequestProcessor implements Runnable {

    private ServiceProvider serviceProvider;
    private Socket socket;

    @Override
    public void run() {

        try (
            ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
            ObjectInputStream  ois = new ObjectInputStream(socket.getInputStream());) {

            Request request = (Request) ois.readObject();
            Response response = getResponse(request);
            oos.writeObject(response);
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    private Response getResponse(Request request) {
        Object service = serviceProvider.getService(request.getServiceName());

        Method method = null;

        try {
            method = service.getClass().getMethod(request.getMethodName(), request.getArgsType());
            Object invoke = method.invoke(service, request.getArgs());
            return Response.success(invoke);
        } catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
            e.printStackTrace();
            return Response.fail(e.getMessage());
        }
    }

}
